#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author:BINGO
# datetime:2018/10/30 下午 04:58
# software: PyCharm
from code2.FindStreetDetail import findStreetDetailByAnJuKe
from code2.db_utils import findStreetName, insertDetail, insertErr, getConnect, findStreetNameByErr, delStreetFromErr
import random
import sys
import datetime
import time


def main():
    # 获得所有需要查询的街道对象
    allStreetDatas = findStreetName()
    db = getConnect()
    try:
        # 遍历
        for i in range(len(allStreetDatas)):
            time.sleep(int(random.random() * 10))
            details = findStreetDetailByAnJuKe(allStreetDatas[i], doTime)
            if len(details) != 0:
                for d in details:
                    insertDetail(d, db)
            else:
                insertErr(allStreetDatas[i].street, '', db)
    except Exception as e:
        print(e)
    finally:
        db.close()


def second():
    db = getConnect()
    errStreetDatas = findStreetNameByErr(db)
    try:
        for detail in errStreetDatas:
            time.sleep(int(random.random() * 10))
            details = findStreetDetailByAnJuKe(detail, doTime)
            if len(details) != 0:
                for d in details:
                    # 写入成功
                    insertDetail(d, db)
                    # 从err表中删除
                    delStreetFromErr(d, db)
            else:
                print('查询失败：===》' + detail.street)
    except Exception as e:
        print(e)
    finally:
        db.close()


if __name__ == '__main__':
    doTime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    # 第一次执行
    main()
    # 第二次执行
    second()
